﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;

namespace LoL_Mastery_Manager
{
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Windows.Threading;


    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region DLL Calls
        [DllImportAttribute("User32.dll")]
        static extern short GetKeyState(int keyFlags);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        private static extern IntPtr mouseEvent(uint dwFlags, int dx, int dy, IntPtr dwDAta, IntPtr dwExtraInfo);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWindow(IntPtr handleToWindow);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(HandleRef handleToWindow, out Rect lpRect);

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        private static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        #endregion

        #region Dll Enums
        public enum VirtualKeyStates : int
        {
            VK_LBUTTON = 0x01,
            KEY_PRESSED = 0x8000
        }
        #endregion

        #region LoL Client Specific Variables

        private IntPtr handleToLeagueOfLegendsWindow = IntPtr.Zero;
        private System.Windows.Rect leagueOfLegendsRectangle = new Rect();
        double lolWidth = 1280;
        double lolRatio = 1;
        // private Rectangle leagueOfLegendsRectangle = new Rectangle();
        private enum WindowSizes { Big, Small }
        WindowSizes lolSize = WindowSizes.Big;

        #endregion

        #region XML Options File Variables
        private int ClickInterval = 100;
        private int ClickSleepInverval = 50;
        private int LeagueSearchInverval = 5000;
        private int ModifySearchInverval = 75;
        #endregion

        private BackgroundWorker colorCheckerBackgroundWorker;

        private bool loadingBuild = false;

        public MainWindow()
        {
            InitializeComponent();
            
            var trayIconMenuStrip = new ContextMenuStrip();
            
            var resize = new ToolStripMenuItem { Text = "Resize" };
                resize.DropDownItems.Add("1024 x 640", null, x640MenuItemClick);
                resize.DropDownItems.Add("1280 x 800", null, x800MenuItemClick);
            
            trayIconMenuStrip.Items.Add(resize);
            trayIconMenuStrip.Items.Add("About", null, this.AboutMenuItemClick);          
            trayIconMenuStrip.Items.Add("Exit", null, this.ExitMenuItemClick);
            

            var trayIcon = new NotifyIcon();
            trayIcon.Icon = Properties.Resources.Icon_Large;
            trayIcon.Visible = true;
            trayIcon.ContextMenuStrip = trayIconMenuStrip;

            // this.Hide();

            this.colorCheckerBackgroundWorker = new BackgroundWorker { WorkerReportsProgress = true };
            this.colorCheckerBackgroundWorker.DoWork += this.ColorCheckerDoWork;
            this.colorCheckerBackgroundWorker.ProgressChanged += this.ColorCheckerProgressChanged;

            colorCheckerBackgroundWorker.RunWorkerAsync();
        }

        private void DragWindow(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DragMove();
            }
            catch
            {
            }
        }

        #region Background Worker

        /// <summary>
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="eventArgs">
        /// The event args.
        /// </param>
        private void ColorCheckerDoWork(object sender, DoWorkEventArgs eventArgs)
        {
            // Cast sender as Background Worker
            var worker = sender as BackgroundWorker;

            // Ensure that sender is not null
            if (worker == null)
            {
                throw new NullReferenceException();
            }

            // Retrieve the current Search Interval
            var sleepTime = Properties.Settings.Default.ModifySearchInterval;

            while (true)
            {
                if (IsWindow(this.handleToLeagueOfLegendsWindow))
                {
                    worker.ReportProgress(6);
                    this.UpdateWindowLocation();

                    lolRatio = leagueOfLegendsRectangle.Width / lolWidth;
                    if (lolRatio == 0.8F && lolSize == WindowSizes.Big)
                    {
                        worker.ReportProgress(3);
                    }
                    else if (lolRatio == 1F && lolSize == WindowSizes.Small)
                    {
                        worker.ReportProgress(4);
                    }
                }
                else
                {
                    // Check to see if the window is activated
                    this.handleToLeagueOfLegendsWindow = FindWindowByCaption(IntPtr.Zero, "PVP.net Client");                    
                    if (IsWindow(this.handleToLeagueOfLegendsWindow))
                    {                        
                        this.UpdateWindowLocation();
                        sleepTime = ModifySearchInverval;
                    }
                    else
                    {
                        // Report that the League of Legends window could not be found
                        worker.ReportProgress(5);
                        sleepTime = LeagueSearchInverval;
                    }
                }

                if (loadingBuild == false)
                {

                }
            }
            
        }

        private bool CheckPage()
        {

        }

        private void ColorCheckerProgressChanged(object sender, ProgressChangedEventArgs eventArgs)
        {
            var result = eventArgs.ProgressPercentage;
            switch (result)
            {
                case 5:
                    // Disable the Resize menu option

                  //((System.Windows.Controls.ContextMenu)this.Resources["TrayIconMenuStrip"])
                  //      .Items
                  //      .Cast<System.Windows.Controls.MenuItem>()
                  //      .Single(x => x.Header.ToString() == "Resize")
                  //      .IsEnabled = false;
                    break;
                case 6:
                    // Enable the Resize menu option

                    //((System.Windows.Controls.ContextMenu)this.Resources["TrayIconMenuStrip"])
                    //    .Items
                    //    .Cast<System.Windows.Controls.MenuItem>()
                    //    .Single(x => x.Header.ToString() == "Resize")
                    //    .IsEnabled = true;

                    break;
                default:
                    System.Windows.Forms.MessageBox.Show("Something went wrong in the background worker Process Changed Function");
                    colorCheckerBackgroundWorker.Dispose();
                    this.Close();
                    System.Windows.Application.Current.Shutdown();
                    break;

            }

            
        }
        #endregion

#region Utility Functions

        public static bool isTopWindow(IntPtr hWnd)
        {
            IntPtr topWindow = GetForegroundWindow();
            if (hWnd == topWindow)
                return true;
            return false;
        }

        private void UpdateWindowLocation()
        {
            Rect rect;
            if (GetWindowRect(new HandleRef(this, this.handleToLeagueOfLegendsWindow), out rect))
            {
                // this.leagueOfLegendsRectangle.OnRender(new DrawingContext())

                this.leagueOfLegendsRectangle.X = rect.Left;
                this.leagueOfLegendsRectangle.Y = rect.Top;
                this.leagueOfLegendsRectangle.Width = rect.Right - rect.Left;
                this.leagueOfLegendsRectangle.Height = rect.Bottom - rect.Top;

                // Insert the window to the top if the Lol window is the top window, and the user is not loading a build or currently holding down the left key
                if (isTopWindow(this.handleToLeagueOfLegendsWindow) && loadingBuild == false && (GetKeyState((int)VirtualKeyStates.VK_LBUTTON) & 0x8000) != (int)VirtualKeyStates.KEY_PRESSED)
                {
                    Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate 
                    {
                        // Set this form to top
                        this.Activate();
                    }
                    , null);

                    //this.Invoke((Action)(() => 
                    //{
                        
                    //}));
                }
            }
            else
            {
                System.Windows.MessageBox.Show("GetWindowRect had an error");
            }
        }

#endregion

        private void AboutMenuItemClick(object sender, EventArgs e)
        {

        }

        private void ExitMenuItemClick(object sender, EventArgs e)
        {
            this.Show();
            this.colorCheckerBackgroundWorker.Dispose();
            System.Windows.Application.Current.Shutdown();
        }

        private void x640MenuItemClick(object sender, EventArgs e)
        {

        }

        private void x800MenuItemClick(object sender, EventArgs e)
        {

        }
    }
}
